package com.lv.suyiyong.hfr.ui

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseActivity
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.common.widget.linkbar.ZFlowLayout
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.adapter.RvTabColorAdapter
import com.lv.service.bean.GoodsBean
import com.lv.service.bean.SearchBean
import com.lv.service.bean.SearchGoodsBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.HomeSearch
import com.lv.service.repo.HomeSearchDbHelper
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.SearchGoodsAdapter
import com.lv.suyiyong.hfr.databinding.ActivityHomeSearchBinding
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/6 10:33 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：首页搜索
 */
@Route(path = ARoutUtils.HomeSearchActivity)
class HomeSearchActivity : BaseActivity<ActivityHomeSearchBinding>(), View.OnClickListener {
    @Autowired(name = "search")
    @JvmField
    var search: String = ""

    @Autowired(name = "searchCode")
    @JvmField
    var mSearchCode: String = ""

    private var mFcaid: String = ""
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private val mParmasMap = mutableMapOf<String, String>()
    private var mTabBeans = mutableListOf<CommonSelectedBean>()
    private var mSearchBeans = mutableListOf<SearchGoodsBean>()
    private var mTabAdapter: RvTabColorAdapter? = null
    private var mSearchAdapter: SearchGoodsAdapter? = null
    private var mSearch = mutableListOf<String>()
    private var mHotSearch = mutableListOf<String>()
    private val mViewList = mutableListOf<View>()
    private val mHotViewList = mutableListOf<View>()
    private var mExpend: Boolean = false //是否展开
    private var mHotExpent: Boolean = false //是否展开
    private var mLoading: Boolean = true //是否有
    private var mLlHistory: LinearLayout? = null
    private var mRvTab: RecyclerView? = null
    private var mZFlowLayout: ZFlowLayout? = null
    private var mZFlowLayoutHot: ZFlowLayout? = null
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val serviceViewModel: ServiceViewModel by viewModel()
    override fun getLayoutRes() = R.layout.activity_home_search
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@HomeSearchActivity, viewTop)
            initSingleClickListener(ivBackTop, vSearch)
        }
    }


    override fun initConfig() {
        super.initConfig()

        if (search.isNotEmpty()) {
            mBinding.searchVM = search
        }
        mBinding.etSearch.paint.isFakeBoldText = !TextUtils.isEmpty(search)
        initTabAdapter()
        searchPagetally()
    }

    private fun initTabAdapter() {
//        val linearFactoryLayoutManager: LinearLayoutManager =
//            object : LinearLayoutManager(this) {
//                //禁止竖向滑动 RecyclerView 为垂直状态（VERTICAL）
//                override fun canScrollVertically(): Boolean {
//                    return false
//                }
//            }
//        mBinding.rvContent.layoutManager = linearFactoryLayoutManager
        mSearchAdapter = SearchGoodsAdapter(mSearchBeans)
        mBinding.rvContent.adapter = mSearchAdapter
        val topHeader =
            View.inflate(this@HomeSearchActivity, R.layout.home_search_header, null)
        mLlHistory = topHeader.findViewById<LinearLayout>(R.id.ll_history)
        mRvTab = topHeader.findViewById<RecyclerView>(R.id.rv_tab)
        mZFlowLayout = topHeader.findViewById<ZFlowLayout>(R.id.flow_view_z)
        mZFlowLayoutHot = topHeader.findViewById<ZFlowLayout>(R.id.flow_view_hot)
        val ivClear = topHeader.findViewById<ImageView>(R.id.iv_clear)
        ivClear.setOnClickListener(this)
        mSearchAdapter?.addHeaderView(topHeader)
        mBinding.rvContent.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(10.0f), SizeUtils.dp2px(10.0f), true
            )
        )

        mTabAdapter = RvTabColorAdapter(mTabBeans)
        mRvTab?.adapter = mTabAdapter

        mTabAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            val index = mTabBeans.indexOfFirst { it.selected }
            if (position == index) {
                return@OnPositionTListener
            }
            if (index >= 0) {
                mTabBeans[index].selected = false
                mTabAdapter?.notifyItemChanged(index, R.id.tv_name)
            }
            mTabBeans[position].selected = true
            mTabAdapter?.notifyItemChanged(position, R.id.tv_name)
            mFcaid = mTabBeans[position].tag
            mBinding.refreshLayout.autoRefresh()
        }
    }


    override fun initData() {
        super.initData()
        addFlowView()
    }


    private fun searchPagetally() {
        mParmasMap["fcaid"] = mFcaid
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    serviceViewModel.searchPagetally(page, pageSize, mParmasMap)
                }
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<SearchBean> { code, data, message, result ->
                if (mLoading) {
                    mLoading = false
                    val attached = data?.attached
                    val hotSearch = attached?.hotSearch
                    mHotSearch.clear()
                    hotSearch?.let {
                        mHotSearch.addAll(hotSearch)
                    }
                    setHotFlowData()
                    mTabBeans.clear()
                    val category = attached?.category
                    category?.forEach {
                        mTabBeans.add(CommonSelectedBean(it.name, "${it.fcaid}"))
                    }
                    if (mTabBeans.isNotEmpty()) {
                        mTabBeans[0].selected = true
                    }
                    mTabAdapter?.notifyDataSetChanged()
                }

                val items = data?.items
                MyUtils.recyclerviewSetData(
                    page, pageSize, mBinding.refreshLayout, mSearchBeans, items, mSearchAdapter
                )

            }
            onBizError<GoodsBean> { code, message, data ->

            }
        }
        data.onFailure {

        }
    }

    override fun initEvents() {
        super.initEvents()
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                searchPagetally()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                searchPagetally()
            }
        })
        mBinding.etSearch.setOnEditorActionListener { v, actionId, event ->
            KeyboardUtils.hideSoftInput(mBinding.etSearch)
            search = mBinding.etSearch.text.toString().trim()
            if (TextUtils.isEmpty(search)) {
                showToast("请输入要搜索的商品/门店")
                false
            } else {
                saveSearchWord(search)
                true
            }
        }

        mBinding.etSearch.addTextChangedListener { text ->
            if (TextUtils.isEmpty(text)) {
                search = ""
                mBinding.etSearch.paint.isFakeBoldText = false
            } else {
                search = text.toString()
                mBinding.etSearch.paint.isFakeBoldText = true
            }
        }

    }

    private fun saveSearchWord(searchWord: String) {
        val homeSearch = HomeSearch(searchWord, searchWord, false)
        HomeSearchDbHelper.insertHomeSearch(this@HomeSearchActivity, homeSearch)

        for (i in 0 until mSearch.size) {
            if (mSearch[i] == searchWord) {
                mSearch.removeAt(i)
                break
            }
        }
        mSearch.add(0, searchWord)
        mLlHistory?.visibility = View.VISIBLE
        mZFlowLayout?.visibility = View.VISIBLE
        setFlowData()
        mBinding.searchVM = searchWord
//        viewModel.liveSearchData.value = searchWord
        search = searchWord
        ARouter.getInstance().build(ARoutUtils.HomeSearchResultActivity)
            .withString("search", search).navigation()
        //发消息通知列表刷新
//        LiveEventBus
//            .get(LiveEventUtils.REFRESH_SEARCH_PAGE_KEY, String::class.java)
//            .post("HomeSearchActivity")
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back_top -> finish()
            R.id.iv_clear -> {
                HomeSearchDbHelper.deleteAllHomeSearch(this@HomeSearchActivity)
                mZFlowLayout?.removeAllViews()
                mLlHistory?.visibility = View.GONE
                mZFlowLayout?.visibility = View.GONE
                mBinding.etSearch.setText("")
                search = ""
                mSearch.clear()
            }

            R.id.v_search -> {
                KeyboardUtils.hideSoftInput(mBinding.etSearch)
                search = mBinding.etSearch.text.toString().trim()
                if (TextUtils.isEmpty(search)) {
                    showToast("请输入要搜索的商品/门店")
                    false
                } else {
                    saveSearchWord(search)
                    true
                }
            }
        }
    }

    private fun addFlowView() {

        lifecycleScope.launch {
            val homeSearch: List<HomeSearch> =
                HomeSearchDbHelper.getAllHomeSearch(this@HomeSearchActivity)
            val reversed = homeSearch.reversed()
            reversed.let {
                mSearch.clear()
                reversed.forEach { item ->
                    mSearch.add(item.name ?: "")
                }
            }


            if (mSearch.isEmpty()) {
                mLlHistory?.visibility = View.GONE
                mZFlowLayout?.visibility = View.GONE
            } else {
                mLlHistory?.visibility = View.VISIBLE
                mZFlowLayout?.visibility = View.VISIBLE
            }

            setFlowData()

            mZFlowLayout?.setOnTagClickListener { view, position ->
                val key = mSearch[position]
                saveSearchWord(key)

            }


        }
    }

    private fun setFlowData() {
        mViewList.clear();
        for (i in 0 until mSearch.size) {
            val textChild = LayoutInflater.from(this@HomeSearchActivity)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout,
                    mZFlowLayout, false
                ) as TextView
            textChild.text = mSearch[i]
            mViewList.add(textChild)
        }

        mZFlowLayout?.setChildren(mViewList)
        mZFlowLayout?.viewTreeObserver?.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mZFlowLayout?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
                val lineCount = mZFlowLayout?.lineCount ?: 0 //行数
                val twoLineViewCount = mZFlowLayout?.twoLineViewCount ?: 0  //前两行里面view的个数
                val expandLineViewCount = mZFlowLayout?.expandLineViewCount ?: 0 ///展开时显示view的个数
                if (lineCount > 2 && !mExpend) {  //默认展示2行，其余折叠收起，最多展示5行
                    initIvClose(twoLineViewCount, expandLineViewCount);
                } else {
                    initIvOpen(twoLineViewCount, expandLineViewCount)
                }

            }
        })
    }

    /**
     * 热门搜索
     */
    private fun setHotFlowData() {
        mHotViewList.clear()
        for (element in mHotSearch) {
            val textChild = LayoutInflater.from(this@HomeSearchActivity)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout, mZFlowLayoutHot, false
                ) as TextView
            textChild.text = element
            mHotViewList.add(textChild)
        }
        mZFlowLayoutHot?.setChildren(mHotViewList)
        mZFlowLayoutHot?.viewTreeObserver?.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mZFlowLayoutHot?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
                val lineCount = mZFlowLayoutHot?.lineCount ?: 0 //行数
                val twoLineViewCount = mZFlowLayoutHot?.twoLineViewCount ?: 0  //前两行里面view的个数
                val expandLineViewCount = mZFlowLayoutHot?.expandLineViewCount ?: 0 ///展开时显示view的个数
                if (lineCount > 2 && !mHotExpent) {  //默认展示2行，其余折叠收起，最多展示5行
                    initIvHotClose(twoLineViewCount, expandLineViewCount);
                } else {
                    initIvHotOpen(twoLineViewCount, expandLineViewCount)
                }

            }
        })
        mZFlowLayoutHot?.setOnTagClickListener { view, position ->
            val key = mHotSearch[position]
            saveSearchWord(key)

        }

    }


    private fun initIvClose(twoLineViewCount: Int, expandLineViewCount: Int) {
        mExpend = false
        mViewList.clear()
        for (i in 0 until twoLineViewCount) {
            val textView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout,
                    mZFlowLayout,
                    false
                ) as TextView
            textView.text = mSearch.get(i)
            mViewList.add(textView)
        }

        if (expandLineViewCount > twoLineViewCount) {
            //展开按钮
            val imageView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.img_record_search_tag,
                    mZFlowLayout,
                    false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_down)
            imageView.setOnClickListener { v: View? ->
                initIvOpen(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mViewList.add(imageView)
        }
        mZFlowLayout?.setChildren(mViewList)
        mZFlowLayout?.viewTreeObserver?.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mZFlowLayout?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
                val lineCount: Int = mZFlowLayout?.lineCount ?: 0
                val twoLineViewCount: Int = mZFlowLayout?.twoLineViewCount ?: 0
                if (lineCount > 2) {
                    initIvClose(
                        twoLineViewCount - 1,
                        mZFlowLayout?.expandLineViewCount ?: 0
                    )
                }
            }
        })
    }

    private fun initIvOpen(twoLineViewCount: Int, expandLineViewCount: Int) {
        mExpend = true
        mViewList.clear()
        for (i in 0 until expandLineViewCount) {
            val textView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout,
                    mZFlowLayout,
                    false
                ) as TextView
            textView.text = mSearch[i]
            mViewList.add(textView)
        }
        if (expandLineViewCount > twoLineViewCount) {
            //收起按钮
            val imageView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.img_record_search_tag,
                    mZFlowLayout,
                    false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_up)
            imageView.setOnClickListener { v: View? ->
                initIvClose(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mViewList.add(imageView) //不需要的话可以不添加
        }
        mZFlowLayout?.setChildren(mViewList)
    }

    private fun initIvHotClose(twoLineViewCount: Int, expandLineViewCount: Int) {
        mHotExpent = false
        mHotViewList.clear()
        for (i in 0 until twoLineViewCount) {
            val textView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout, mZFlowLayoutHot, false
                ) as TextView
            textView.text = mHotSearch.get(i)
            mHotViewList.add(textView)
        }

        if (expandLineViewCount > twoLineViewCount) {
            //展开按钮
            val imageView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.img_record_search_tag, mZFlowLayoutHot, false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_down)
            imageView.setOnClickListener { v: View? ->
                initIvHotOpen(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mHotViewList.add(imageView)
        }
        mZFlowLayoutHot?.setChildren(mHotViewList)
        mZFlowLayoutHot?.viewTreeObserver?.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mZFlowLayoutHot?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
                val lineCount: Int = mZFlowLayoutHot?.lineCount ?: 0
                val twoLineViewCount: Int = mZFlowLayoutHot?.twoLineViewCount ?: 0
                if (lineCount > 2) {
                    initIvHotClose(
                        twoLineViewCount - 1,
                        mZFlowLayoutHot?.expandLineViewCount ?: 0
                    )
                }
            }
        })
    }

    private fun initIvHotOpen(twoLineViewCount: Int, expandLineViewCount: Int) {
        mHotExpent = true
        mHotViewList.clear()
        for (i in 0 until expandLineViewCount) {
            val textView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout, mZFlowLayoutHot, false
                ) as TextView
            textView.text = mHotSearch[i]
            mHotViewList.add(textView)
        }
        if (expandLineViewCount > twoLineViewCount) {
            //收起按钮
            val imageView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.img_record_search_tag,
                    mZFlowLayoutHot, false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_up)
            imageView.setOnClickListener { v: View? ->
                initIvHotClose(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mHotViewList.add(imageView) //不需要的话可以不添加
        }
        mZFlowLayoutHot?.setChildren(mHotViewList)
    }

}